<?php
class LetterNumber extends AppModel {
    var $validate = array(
        'no_start' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => 'numeric',
            'message' => 'This field cannot be left blank and must be numeric'
        ),
        'no_end' => array(
            'required' => true,
            'allowEmpty' => false,
            'rule' => 'numeric',
            'message' => 'This field cannot be left blank and must be numeric'
        ),
        'active' => array(
            'rule' => 'vActive',
            'message' => 'There is already active number'
        )
    );
    
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'created_by',
            'fields' => array('id', 'name')
        )
    );
    var $hasMany = array(
        'LetterOut' => array(
            'fields' => array('id')
        )
    );
    
    var $cacheQueries = true;
    
    function vActive() {
        $conditions = array();
        $conditions[$this->name . '.active'] = 1;
        
        if ( isset($this->id) && $this->id ) {
            $conditions[$this->name . '.id <>'] = $this->id;
        }
        
        $active = $this->find('count', array(
            'conditions' => $conditions
        ));
        
        if ( $active && $this->data[$this->name]['active'] ) {
            return false;
        }
        
        return true;
    }
    
    function getStock($id) {
        return $this->query(
            "SELECT (((LetterNumber.no_end-LetterNumber.no_start)+1) - COUNT(LetterOut.id)) as stock FROM letter_outs LetterOut
             LEFT JOIN letter_numbers LetterNumber ON LetterNumber.id = LetterOut.letter_number_id
            WHERE LetterOut.letter_number_id = $id AND LetterNumber.id = $id"
        );
    }
}
?>